// pages/Project-management/travel/travel.js
import { fetchTravelData, getImage } from '../../../api/travel';

Page({
  data: {
    projectId: null,
    projectName: '',
    currentDate: '',
    travelList: [],
    showModal: false,
    image: ''
  },

  onLoad(options) {
    const { projectId, projectName } = options;
    this.setData({ projectId, projectName });
    const date = new Date().toISOString().slice(0, 7);
    this.setData({ currentDate: date });
    this.fetchTravelData(projectId, date);
  },

  fetchTravelData(projectId, date) {
    fetchTravelData(projectId, date).then(response => {
      if (response.code === 1) {
        console.log(response);
        this.setData({ travelList: response.data });
      } else {
        console.error('Failed to fetch travel data');
      }
    }).catch(error => {
      console.error('Error fetching travel data:', error);
    });
  },

  onDateChange(event) {
    const date = event.detail.value;
    this.setData({ currentDate: date });
    this.fetchTravelData(this.data.projectId, date);
  },

  showVoucher(event) {
    const imageName = event.currentTarget.dataset.voucher;
    getImage(imageName).then(response => {
      const imageUrl = 'data:image/png;base64,' + response.data.data;
      this.setData({
        image: imageUrl,
        showModal: true
      });
    }).catch(error => {
      console.error('Failed to fetch image', error);
    });
  },

  arrayBufferToBase64(buffer) {
    let binary = '';
    const bytes = new Uint8Array(buffer);
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return wx.arrayBufferToBase64 ? wx.arrayBufferToBase64(buffer) : btoa(binary);
  },

  hideModal() {
    this.setData({
      showModal: false,
      image: ''
    });
  },

  addTravel() {
    const { projectId, projectName } = this.data;
    wx.navigateTo({
      url: `/pages/Project-management/addTravel/addTravel?projectId=${projectId}&projectName=${projectName}`
    });
  },

});
